package com.yyw.foodie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.yyw.foodie.bo.orders.CommentsOrderItemBo;
import com.yyw.foodie.enums.YesOrNoEnums;
import com.yyw.foodie.exceptions.OrderStatusException;
import com.yyw.foodie.mapper.ItemsCommentsMapper;
import com.yyw.foodie.pojo.ItemsCommentsEntity;
import com.yyw.foodie.pojo.OrderStatusEntity;
import com.yyw.foodie.pojo.OrdersEntity;
import com.yyw.foodie.service.ItemsCommentsService;
import com.yyw.foodie.service.OrderStatusService;
import com.yyw.foodie.service.OrdersService;
import com.yyw.foodie.utils.DesensitizationUtil;
import com.yyw.foodie.utils.PagedGridResult;
import com.yyw.foodie.vo.CommentLevelVo;
import com.yyw.foodie.vo.ItemCommentVO;
import com.yyw.foodie.vo.center.comments.QueryCommentsVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品评价表  服务实现类
 * </p>
 *
 * @author yiyw
 * @since 2021-05-22
 */
@Service
public class ItemsCommentsServiceImpl extends ServiceImpl<ItemsCommentsMapper, ItemsCommentsEntity> implements ItemsCommentsService {

    @Autowired
    private ItemsCommentsMapper itemsCommentsMapper;

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderStatusService orderStatusService;

    @Override
    public CommentLevelVo getCommentLevelByItemId(String itemId) {
        CommentLevelVo vo = new CommentLevelVo();
        Integer level1 = getCommentLevelByItemIdAndLevel(itemId, 1);
        Integer level2 = getCommentLevelByItemIdAndLevel(itemId, 2);
        Integer level3 = getCommentLevelByItemIdAndLevel(itemId, 3);
        vo.setGoodCounts(level1);
        vo.setNormalCounts(level2);
        vo.setBadCounts(level3);
        vo.setTotalCounts(level1 + level2 + level3);
        return vo;
    }

    @Override
    public PagedGridResult getCommentPageByItemId(String itemId, Integer level, Integer pageSize, Integer page) {
        PageHelper.startPage(page, pageSize);
        List<ItemCommentVO> list = itemsCommentsMapper.page(itemId, level);
        for (ItemCommentVO vo : list) {
            vo.setNickname(DesensitizationUtil.commonDisplay(vo.getNickname()));
        }
        PagedGridResult grid = PagedGridResult.setterPagedGrid(list, page);
        return grid;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveComments(List<CommentsOrderItemBo> commentsOrderItemBoList, String orderId, String userId) {
        //  收集评论的订单 并保存
        if (!CollectionUtils.isEmpty(commentsOrderItemBoList)) {
            List<ItemsCommentsEntity> collect = commentsOrderItemBoList.stream().map(e -> {
                ItemsCommentsEntity commentsEntity = new ItemsCommentsEntity();
                BeanUtils.copyProperties(e, commentsEntity);
                commentsEntity.setUserId(userId);
                commentsEntity.setItemId(e.getItemId());
                commentsEntity.setItemSpecId(e.getItemSpecId());
                commentsEntity.setSepcName(e.getItemSpecName());
                return commentsEntity;
            }).collect(Collectors.toList());
            // 保存
            boolean saveBatch = saveBatch(collect);
            // 修改订单主表的信息
            LambdaUpdateWrapper<OrdersEntity> updateMain = Wrappers.<OrdersEntity>lambdaUpdate()
                    .set(OrdersEntity::getIsComment, YesOrNoEnums.是.code)
                    .eq(OrdersEntity::getId, orderId);
            boolean mainResult = ordersService.update(updateMain);
            // 修改订单状态
            LambdaUpdateWrapper<OrderStatusEntity> updateStatus = Wrappers.<OrderStatusEntity>lambdaUpdate().set(OrderStatusEntity::getCommentTime, new Date())
                    .eq(OrderStatusEntity::getOrderId, orderId);
            boolean statusResult = orderStatusService.update(updateStatus);
            if (!saveBatch || !mainResult || !statusResult) {
                throw new OrderStatusException("订单保存评论或修改状态信息失败");
            }
        }
    }

    @Override
    public PagedGridResult getCommentInfoByPage(String userId, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<QueryCommentsVo> list = itemsCommentsMapper.pageByUser(userId);
        PagedGridResult result = PagedGridResult.setterPagedGrid(list, page);
        return result;
    }

    /**
     * 根据商品ID、评价等级获取评价数量
     *
     * @param itemId 商品ID
     * @param level  评价等级
     * @return 评价数量
     */
    public Integer getCommentLevelByItemIdAndLevel(String itemId, Integer level) {
        QueryWrapper<ItemsCommentsEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ItemsCommentsEntity::getItemId, itemId).eq(ItemsCommentsEntity::getCommentLevel, level);
        return count(queryWrapper);
    }

}
